package com.erp4j.dynamicfield.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.erp4j.dynamicfield.entity.FieldDefinition;
import com.erp4j.dynamicfield.mapper.FieldDefinitionMapper;
import com.erp4j.dynamicfield.service.FieldDefinitionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class FieldDefinitionServiceImpl extends ServiceImpl<FieldDefinitionMapper, FieldDefinition>
        implements FieldDefinitionService {

    @Override
    public List<FieldDefinition> getFieldsByModuleId(Long moduleId) {
        QueryWrapper<FieldDefinition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("module_id", moduleId)
                   .orderByAsc("sort_order");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public FieldDefinition addField(FieldDefinition field) {
        // 如果是扩展字段，生成系统字段名
        if (!field.getIsBaseField()) {
            String systemFieldName = generateSystemFieldName(
                field.getModuleId(), 
                field.getFieldType()
            );
            field.setSystemFieldName(systemFieldName);
        }
        
        baseMapper.insert(field);
        return field;
    }

    /**
     * 生成系统字段名：ext_<类型>_<序号>
     * 例如：ext_str_1, ext_date_2, ext_num_3
     */
    private String generateSystemFieldName(Long moduleId, String fieldType) {
        // 简化字段类型名称
        String typeSuffix = getTypeSuffix(fieldType);
        
        // 查询当前模块同类型的扩展字段数量
        QueryWrapper<FieldDefinition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("module_id", moduleId)
                   .eq("is_base_field", false)
                   .like("system_field_name", "ext_" + typeSuffix + "_");
        
        Long count = baseMapper.selectCount(queryWrapper);
        // 序号从1开始
        Long sequence = count + 1;
        
        return "ext_" + typeSuffix + "_" + sequence;
    }

    /**
     * 将字段类型映射为短后缀
     */
    private String getTypeSuffix(String fieldType) {
        switch (fieldType.toLowerCase()) {
            case "string":
                return "str";
            case "number":
            case "integer":
            case "decimal":
                return "num";
            case "date":
            case "datetime":
                return "date";
            case "boolean":
                return "bool";
            default:
                return "str";
        }
    }

    @Override
    public String getQueryType(Long moduleId, String fieldName) {
        QueryWrapper<FieldDefinition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("module_id", moduleId)
                   .eq("field_name", fieldName);
        
        FieldDefinition field = baseMapper.selectOne(queryWrapper);
        return field != null ? field.getQueryType() : "eq";
    }


    /**
     * 根据模块ID获取扩展字段定义
     */
    @Override
    public List<FieldDefinition> getExtFieldsByModuleId(Long moduleId) {
        return baseMapper.selectExtFieldsByModuleId(moduleId);
    }
}
